package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: gongfy
 * @create: 2020/9/14 16:57
 * @Description:  网关测试类 继承ZuulFilter并@Component注入容器
 */
//@Component  测试时候使用
public class LoginFilterTest extends ZuulFilter {

    //1.定义过滤类型
    @Override
    public String filterType() {
        /*
        * pre: 请求在路由（转发）之前执行
        * routing: 在路有时请求调用
        * post: 在routing和error过滤之后调用
        * error: 处理请求错误时调用
        * */
        return "pre";
    }
    //2.定义过滤器序号，越小越先被执行
    @Override
    public int filterOrder() {
        return 0;
    }
    //3.定义是否被过滤 设置true
    @Override
    public boolean shouldFilter() {
        return true;
    }
    //4.定义过滤器需要过滤的内容
    //需求：校验请求头中是否含有 Authorization
    @Override
    public Object run() throws ZuulException {
        //1.获取request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        //2.获取header
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)){

            requestContext.setSendZuulResponse(false);// 拒绝访问，不在向下路由转发
            requestContext.setResponseStatusCode(200);// 设置状态响应码
            ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHENTICATED);// 此操作需要登录系统
            String jsonString = JSON.toJSONString(responseResult);
            requestContext.setResponseBody(jsonString);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); // "application/json;charset=UTF-8"
            return null;
        }
        return null;
    }
}
